#include "stdafx.h"
#include "m.h"
#include "mcon_i.c"

extern "C" {
STDAPI DllCanUnloadNow(void);
STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv);
STDAPI DllRegisterServer(void);
STDAPI DllUnregisterServer(void);
}


CComModule _Module;
CComObject<CMudos> *mudos=NULL;

BEGIN_OBJECT_MAP(ObjectMap)
	OBJECT_ENTRY(CLSID_MFunction, CMFunction)
	OBJECT_ENTRY(CLSID_MProgram, CMProgram)
	OBJECT_ENTRY(CLSID_MValue, CMValue)
	OBJECT_ENTRY(CLSID_MudOS, CMudos)
END_OBJECT_MAP()

extern "C" int InitCom(HINSTANCE hInstance);
extern "C" int ExitCom();

extern "C" int program_t_size_cpp;
int program_t_size_cpp=sizeof(program_t);

int InitCom(HINSTANCE hInstance)
{
	HRESULT ret;
	BSTR bstrName;
	char buf[256];
	char dll[256];
	long size;
	Cw2c w2c;
	static int have_init=0;
	if(!have_init){
		_Module.Init(ObjectMap, hInstance);

		ret=StringFromCLSID(CLSID_MudOS,&bstrName);
		if(ret==S_OK){
			w2c.in(bstrName);
			CoTaskMemFree(bstrName);
			sprintf(buf,"CLSID\\%s",w2c.out());
			size=sizeof(dll);
			if(RegQueryValue(HKEY_CLASSES_ROOT,buf,dll,&size)!=ERROR_SUCCESS){
				DllRegisterServer();
			}
		}
        have_init=1;
    }
	return 0;
}

int ExitCom()
{
	_Module.Term();
	return 0;
}

/////////////////////////////////////////////////////////////////////////////
// Used to determine whether the DLL can be unloaded by OLE

STDAPI DllCanUnloadNow(void)
{
	return (_Module.GetLockCount()==0) ? S_OK : S_FALSE;
}

/////////////////////////////////////////////////////////////////////////////
// Returns a class factory to create an object of the requested type

STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, LPVOID* ppv)
{
	return _Module.GetClassObject(rclsid, riid, ppv);
}

/////////////////////////////////////////////////////////////////////////////
// DllRegisterServer - Adds entries to the system registry


STDAPI DllRegisterServer(void)
{
	// registers object, typelib and all interfaces in typelib
	return _Module.RegisterServer(TRUE);
}

/////////////////////////////////////////////////////////////////////////////
// DllUnregisterServer - Removes entries from the system registry

STDAPI DllUnregisterServer(void)
{
	_Module.UnregisterServer();
	return S_OK;
}


IDispatch *GetMudOs()
{
    if(!mudos){
		mudos=new CComObject<CMudos>;
	    mudos->AddRef();
    }
	mudos->AddRef();
	return mudos;
}
